package com.mobile.framework.exception;

import java.io.PrintStream;
import java.io.PrintWriter;

/**
 * Base exception class for all exceptions in the system.
 */
public abstract class BaseException extends Exception {
	protected Throwable rootCause = null;

	private String messageKey = "error.unknown";

	private Object[] messageArgs = null;

	public BaseException() {
		super();
	}

	public BaseException(Throwable cause) {
		this.rootCause = cause;
		this.messageArgs = new String[] { rootCause.getMessage() };
	}

	public BaseException(String key) {
		this(key, null);
	}

	public BaseException(String key, Object[] args) {
		this(key, args, null);
	}

	public BaseException(String key, Object[] args, Throwable cause) {
		this.messageKey = key;
		this.messageArgs = args;
		this.rootCause = cause;
	}

	public String getMessageKey() {
		return messageKey;
	}

	public Object[] getMessageArgs() {
		return messageArgs;
	}

	public Throwable getRootCause() {
		return rootCause;
	}

	/**
	 * Sets the messageArgs.
	 * 
	 * @param messageArgs
	 *            The messageArgs to set
	 */
	public void setMessageArgs(Object[] messageArgs) {
		this.messageArgs = messageArgs;
	}

	/**
	 * Sets the messageKey.
	 * 
	 * @param messageKey
	 *            The messageKey to set
	 */
	public void setMessageKey(String messageKey) {
		this.messageKey = messageKey;
	}

	@Override
	public void printStackTrace() {
		printStackTrace(System.err);
	}

	@Override
	public void printStackTrace(PrintStream outStream) {
		printStackTrace(new PrintWriter(outStream));
	}

	@Override
	public void printStackTrace(PrintWriter writer) {
		super.printStackTrace(writer);

		if (getRootCause() != null) {
			getRootCause().printStackTrace(writer);
		}
		writer.flush();
	}
}